 <?


class CTRLnewsletter extends CONTROL {

	function __construct( $vars ) {
		global $Object;
		
		$this->_addvars( $vars );

		if( $this->action != "list" )
			$Object = $this->create_object();
	}
	
#	New Object.
	function filter_new() {
		global $Object;

		if( $this->parent ) $new = "$('$this->parent').seed([" . $Object->render_core_json() . "], 0);";

		$Object->set( "meta", array( "year"=> date( "Y" ), "theme"=> engine_get( "theme" )), 1 );

		return $new . $this->filter_edit(); 
	}


#	Edit Object.
	function filter_edit() {
		global $DB, $Engine, $Object, $Page;
		
		// vars id
		if( !$this->vars->id ) $this->vars->id = $Object->id;
		
		// mail template
		$mail_settings	= $DB->get_key( "json.object", "ID = " . (int) engine_get( 'mailer.content.default' ), "json" );
		$mail_settings	= json_decode( $mail_settings );
		$template = $Engine->text->get( $mail_settings->html_template, "long", engine_get( 'lang.master' ));
		if( count( explode( '</style>', $template ) >= 1 )){
			
			// css
			$styles 	= explode( '<br />', nl2br( array_shift( explode( '</style>', $template ))));
			//$styles 	= explode( '\n', array_shift( explode( '</style>', $template )));
			$counter	= 0;
			foreach( $styles as $style ) {
				$style = substr( str_replace( array("\r\n", "\r", "\n"), " ", $style ), 1);
				if( $counter > 0 && substr( $style, 0, 1 ) != '@' && !empty( $style )) {
					//echo '#lightbox_textid ' . $style;
					$stylers .= '.field ' . $style . ' ';
				}
				$counter++;
			}
			//$stylers = implode( '\n', $stylers );
			
			// html 
			$template = '<style type="text/css">' . $stylers . '</style>' . array_pop( explode( '</style>', $template ));
			//$template = array_pop( explode( '</style>', $template ));
		}
				
		// page
		$Page = new PAGE((int) $mail_settings->location );

		// replacers
		$replacers = array(
			"%date%"	=> (( $Object->get( 'flog' )) ? date( "d.m Y", strtotime( $Object->get( "flog" ))) : date( "d.m Y" )),
			"%issue%"	=> (( $Object->id ) ? $Object->id : 'xxx' ),
			"%title%"	=> (( $Object->get( "name" )) ? $this->title = $Object->get( "name" ) : '' ),
			"%style%"	=> PUBLIC_THEME . "/mailer",
			"%url"		=> $Page->url( "?letterid=". (( $Object->id ) ? $Object->id : 'xxx' )),
			"%year%"	=> (( $Object->get( 'flog' )) ? date( "Y", strtotime( $Object->get( "flog" ))) : date( "Y" ))
		);
		
		// side replacers (images)
		if( $Object->hasMedia() && $media = $Object->media->reference( "media.img" )) {
			foreach ( $media as $el ) $side[] = "<img src='". engine_get( "url" ) ."/public.img?id=$el&sze={$mail_settings->imgsze}' />";
			$replacers[ "%side%" ] = implode( "\n", $side );
		} else {
			$replacers[ "%side%" ] = "<i>no images yet..</i>";
		}
		
		// mods in mail template
		if( $mail_settings->mods ) {
		
			$modules	= array();
			$mods 		= $mail_settings->mods;
			$modcon		= new MOD_CONSTRUCT();
			foreach((array) $mods as $column => $ids ) {
				
				if( count( $ids )) foreach( $ids as $id ) {
			
					$Mod = $modcon->call(( int ) $id );
					$modules[ "%mods:$column%" ] .= utf8_encode( $Mod->output());
				}
				$replacers[ "%mods:$column%" ] = $modules[ "%mods:$column%" ];
			}
		}
				
		// text replace
		$cont	= array();
		foreach( $Engine->text->filter( $Object->get( "textid" ), 'long' ) as $language => $text ) {
			
			$wrapper = array( "wrap" => str_replace( array_keys( $replacers ), array_values( $replacers ), $template ));
			
			$volume = str_replace( '%content%', $text, $template );
			$volume	= str_replace( array_keys( $replacers ), array_values( $replacers ), $volume );
			$cont[ $language ]	= $volume;
			
			$lang_values[ $language ] = utf8_encode( $text );
		}		
						
		$type = $this->vars->type;
		
		$open = $done = 0;
		if( $done = count( $DB->reference( "newsletter", (int) $this->vars->id, "user", null, "social" ))) {
			$open = (int) $DB->count( "user", "active && lang = '". LANG ."'" ) - $done;
			if( $open < 0 ) $open = 0;
		}
		
		return "
		ref.seed([
			
			new Element( 'h1' ).update( \"Beheer $type '". (( $Object->get( "nameid" ) )? $Engine->text->get( $Object->get( "nameid" ) ) : $Object->id ) . "'\" ),
			new Textfield({ descr:'header $type', type:'$type', parentid:{$Object->id}, textid:". $Object->get( "nameid" ) .", values:". json_encode( $Engine->text->filter( $Object->get( "nameid" ) )) ." }),
			new Lightboxfield({ descr:'text $type', type:'$type', parentid:{$Object->id}, textid:". $Object->get( "textid" ) .", contenteditable:'false', wrapper:" . json_encode( $wrapper ) . ", values:". json_encode( $lang_values ) ." }),
			new Dropbox({ descr:'Beelden', type:'media.img', parenttype:'$type', action:'win', blank:'add image', id:{$Object->id}, uptype:'media', floats:". $this->filter_media( 'media.img' ) ." }),
			new Options({ descr:'Opties', floats: [
				new Ajxfield({ type:'$type', descr:'weergegeven datum', objid:{$Object->id}, field:'flog', value:'{$Object->get('flog')}', extend:'cal' })
			]}),
			new Options({ descr:'Publiceren', active:1, floats: [
				new Element( 'span' ).update( '$open te bereiken gebruikers ($done verzonden)' ),
				new Shift({ type:'$type', descr:'Publiceerbaar', value:{$Object->get( 'active' )}, field:'active', objid:{$Object->id} }),
				new Button({ action: 'example', type: 'newsletter', descr: 'verzend voorbeeld', id:{$Object->id}}),
				new Button({ action: 'publish', type: 'newsletter', descr: 'start publicatie', buffer: 'publicatie gestart', id:{$Object->id}})
			]})
		]);";

	}

	
#	Edit Object.
	function filter_edit_old() {
		global $DB, $Engine, $Object;
		
		$type = $this->vars->type;
		if( !$this->vars->id ) $this->vars->id = $Object->id;
		 
		$done = count( $DB->reference( "newsletter", (int) $this->vars->id, "user", null, "social" ));
		$open = (int) $DB->count( "user", "active && lang = '". LANG ."'" ) - $done;
		if( $open < 0 ) $open = 0;
		
		return "
		ref.seed([
			
			new Element( 'h1' ).update( \"Beheer $type '". (( $Object->get( "nameid" ) )? $Engine->text->get( $Object->get( "nameid" ) ) : $Object->id ) . "'\" ),
			new Textfield({ descr:'name $type', type:'$type', parentid:{$Object->id}, textid:". $Object->get( "nameid" ) .", values:". json_encode( $Engine->text->filter( $Object->get( "nameid" ) )) ." }),
			new Htmlfield({ descr:'text $type', type:'$type', parentid:{$Object->id}, textid:". $Object->get( "textid" ) .", values:". json_encode( $Engine->text->filter($Object->get( "textid" ), 'long' )) ." }),
			new Dropbox({ descr:'Beelden', type:'media.img', parenttype:'$type', action:'win', blank:'add image', id:{$Object->id}, uptype:'media', floats:". $this->filter_media( 'media.img' ) ." }),
			new Options({ descr:'Opties', floats: [
				new Ajxfield({ type:'$type', descr:'weergegeven datum', objid:{$Object->id}, field:'flog', value:'{$Object->get('flog')}', extend:'cal' })
			]}),
			new Options({ descr:'Publiceren', active:1, floats: [
				new Element( 'span' ).update( '$open te bereiken gebruikers ($done verzonden)' ),
				new Shift({ type:'$type', descr:'Publiceerbaar', value:{$Object->get( 'active' )}, field:'active', objid:{$Object->id} }),
				new Button({ action: 'example', type: 'newsletter', descr: 'verzend voorbeeld', id:{$Object->id}}),
				new Button({ action: 'publish', type: 'newsletter', descr: 'start publicatie', buffer: 'publicatie gestart', id:{$Object->id}})
			]})
		]);";

	}
	
#	Render media floats
	function filter_media( $objtype ) {
		global $DB, $Object;
		
		$result = array();
		
		if( $images = $Object->media->filter( $objtype ))
			foreach( $images as $img ) {
				$result[] = array( "id"=> $img['ID'], "type"=> $objtype, "name"=> $objtype, "list"=> array( $img['ID'], json_decode( $img[ 'meta' ])->raw ));
			}
		
		return json_encode( $result );
	}
	

#	Publish example.
	function filter_example() {
		global $Engine;
		
		
		
		$Letter = new MAIL( "html" );
		
		//// LANG SHOULD BE EDITABLE!!!
		$example = $Letter->generate_newsletter( $this->vars->id, "nl" );
		$Letter->send_single(( int ) $Engine->user( 'ID' ));
		
		return $this->comment( "Verzonden naar ". $Engine->user( "mail" ));

	}

#	Publish all.
	function filter_publish() {
		global $DB, $Engine;
		
		//// LANG SHOULD BE EDITABLE!!!
		$Letter	= new MAIL( "html" );
		$Letter->generate_newsletter( $this->vars->id, "nl" );
		
		if( !$done = $DB->reference( "newsletter", (int) $this->vars->id, "user", null, "social" )) $done = array( 0 );

		if( $count = $Letter->send( "ID not in( ". implode( ",", $done ) ." ) && active && lang = '". LANG ."' order by ID", true ))

				$comment = "Publicatie $count nieuwsbrieven succesvol!";
		else	$comment = "Geen resultaat (alreeds verzonden)";
		
		return $this->comment( $comment );
	}
	
}


/*
////////////////  NEWSLETTER ASSETS
if($_tool[1] == "letter") {

////////////////// LIST NEWSLETTERS
	if($_set->action == "list"){ ?>

		ref.seed([
			tag("font", {style:"font-size:18px"}, "<?= ucfirst($_set->vars->descr)?>"), br, br,
			new List({id:ref.id+".lst", tool:'text.letter', descr:'<?=$_set->vars->boxdescr?>', new:'add <?=$DB->type_r( $_set->vars->objtype )?>', meta:ref.vars})
		]);
	
		$(ref.id+".lst").seed(<?= $_set->parse_list() ?>);


////////////////// EDIT NEWSLETTER
	<? } else if($_set->action == "edit" || $_set->action == "edit.new"){ 
		if( $_set->action == "edit.new" ) {
			
			$DB->query("INSERT INTO mod_letter (type, pdate, flog, creator, meta) VALUES (".$_set->vars->objtype.", NOW(), NOW(), ".$Engine->user("ID").", '{\"year\":2010, \"theme\":\"" . engine_get('theme') . "\"}')", 0 );
			$_set->vars->id = $DB->get_key( "text.letter", "active=0 order by ID desc", "ID" );
			?>
			
			if(ref.vars.parent) {
				win.float.list["float_"+ref.vars.type+".<?=$_set->vars->id?>"] = obj = {id:<?=$_set->vars->id?>, type:ref.vars.type, tool:'text.letter', name:"...", descr:"...", objtype:ref.vars.objtype, list:[{ref:'id'}, {ref:'descr'}, '<?=date("d.m y")?>'], meta:{} };
				$(ref.vars.parent).vars.floatlist.push(<?=$_set->vars->id?>);
				$(ref.vars.parent+".tbody").insert({top: new win.trfloat(obj)});
			}
			<?
		}
		
		$letterloc	= $Modcon->request_json( engine_get('style:mod.letter.vars') );
		$letterloc	= $DB->get_key( "page", "ID=".$letterloc->location , "name" );
		
		$_letter	= $DB->get( "text.letter", "ID=". $_set->vars->id, "*, YEAR(pdate) as year, MONTH(pdate) as month, DAY(pdate) as day, HOUR(pdate) as hour" );
		$title		= $Engine->text->filter( $_letter['nameid'] );
		$body		= $Engine->text->filter( $_letter['textid'], "long" );
		$meta		= $_letter['meta'];
		$theme		= json_decode($meta)->theme;
	
		?>
		
		ref.seed([
			tag("font", {style:"font-size:18px"}, "<?= _("Edit ") ?>"), tag("a", {id:ref.id+".h1", href:"http://<?=engine_get('control.public')?>/<?=$letterloc?>&letterid=<?=$_set->vars->id?>", target:"_blank", style:"font-size:18px"}, "issue <?=$_set->vars->id?>"), " (view)", br, br,
			tag("input", {id:ref.id+".title"}), tag("div", {id:ref.id+".text"}),  br, tag("div", {id:ref.id+".objs"}),
			new Button({id:ref.id+".test", type:'letter', action:'button', descr:'test letter', letterid:<?=$_set->vars->id?>, tool:'text.letter', meta:{ value:1 }}),
			new Button({id:ref.id+".init", type:'letter', action:'init.batch', descr:'initiate send loop', letterid:<?=$_set->vars->id?>, tool:'text.letter', meta:{ value:1 }}),
			tag("br"),
			tag("font", {style:"font-size:11px"}, "Note: After initiating the send loop, do not close the browser until all newsletters have been sent. If the sending of newsletters is interrupted for any reason, clicking initiate send loop will resume the process from where it was stopped."),
			tag("div", {id:ref.id+".init.response"}, "idle"),
			tag("div", {id:ref.id+".comment", class:"comment"}),
			new Options({id:ref.id+".options", tool:'group.basic', descr:'Opties', floats: [
				new Shift({id:ref.id+".publish", type:'letter', action:'shift', descr:'is public', tool:'text.letter', meta:{ value:<?=($_letter['active']==1)?1:0;?>, options:[0,1], field:"active", objid:ref.vars.id}})
			], meta:{}})
		]);
		
		$(ref.id+".test").observe("focus", function(e) {
			this.vars.meta.lang = init.lang;
		});

		$(ref.id+".init").observe("focus", function(e) {
			this.vars.meta.lang = init.lang;
		});
		
		[	{id:ref.id+".title", descr:'title', direct:1, parenttype:"letter", parentid:<?=$_letter['ID']?>, traceback:<?= json_encode($_set->vars->traceback) ?>, textid:<?= $_letter['nameid'] ?>, values:<?=($title)?json_encode($title):"{}"?>},
			{id:ref.id+".text", rich:1, descr:'newsletter text', ref:'lettertext', parenttype:"letter", parentid:<?=$_letter['ID']?>, direct:1, textid:<?= $_letter['textid'] ?>, values:<?=($body)?json_encode($body):"{}"?>}
		].each(function(obj){ win.asset.txtfield.build(obj); });

	<? }

}




//////////////////// PUSH


////////////////// LETTER FUNCTIONALITIES
if($_set->action == "button" && $_set->type=="letter") {

	include_once "engine/www/class/MAILER.php";

	$LETTER = new MAILER("html");

	if ($_set->vars->letterid) {

		$LETTER->_generate_newsletter($_set->vars->letterid, $_set->vars->meta->lang, $Engine->user('ID'));
		$LETTER->_send();

		$comment = "Sent a sample newsletter.";
	}

	?>
	xhttp.gfx("<?=$comment?>", $(ref.trg).ancestors()[1].id+".init.response");
	<?
exit(); }

////////////////// LETTER LOOP INIT
if($_set->action == "init.batch" && $_set->type=="letter") {

	?>
	letter_amount = <?= $DB->query_direct( "select count(*) from mod_user where lletter < {$_set->vars->letterid} && lang = '{$_set->vars->meta->lang}'" ) ?>;
	xhttp.gfx("initiated, for "+ letter_amount +" users", ref.trg+".response");
	xhttp.send('control.call.php', {trg:ref.trg, wtype:'push', type:"letter", tool:"text.letter", action:"batch.loop", vars:{letterid:<?=$_set->vars->letterid?>, meta:{lang:'<?=$_set->vars->meta->lang?>'}} });
	$(ref.trg).value = "stop sending";
	$(ref.trg).vars.action = "batch.cancel";
	<?
exit(); }

////////////////// LETTER LOOP LOOP
if($_set->action == "batch.loop" && $_set->type=="letter") {

	?>
	$(ref.trg).tm = setTimeout(function() {
		<?
		include_once "engine/www/class/MAILER.php";
		$LETTER = new MAILER("html");
		if ($_set->vars->letterid) {
		#	$LETTER->_generate_newsletter($_set->vars->letter, $_set->vars->language, $Engine->user('ID'));
			$LETTER->_generate_newsletter($_set->vars->letterid, $_set->vars->meta->lang, "lletter < ". $_set->vars->letterid . " AND lang = \"". $_set->vars->meta->lang . "\" LIMIT 98");
	 		
	 		if( $success = $LETTER->_send() )
				$DB->query("UPDATE mod_user set lletter = " . $_set->vars->letterid . " WHERE ID in(" . implode(", ", $success) . ")");
		}
		?>
		letter_amount -= 98
		xhttp.gfx("remaining: "+ ((letter_amount > 0)? letter_amount: 0), ref.trg+".response"); 
		if( letter_amount < 1)
				xhttp.send('control.call.php', {trg:ref.trg, wtype:'push', type:"letter", tool:"text.letter", action:"loop.end", vars:{letterid:<?=$_set->vars->letterid?>, meta:{lang:'<?=$_set->vars->meta->lang?>'}} });
		else 	xhttp.send('control.call.php', {trg:ref.trg, wtype:'push', type:"letter", tool:"text.letter", action:"batch.loop", vars:{letterid:<?=$_set->vars->letterid?>, meta:{lang:'<?=$_set->vars->meta->lang?>'}} });
	
	
	}, 1000);
	
	<?
exit(); }

////////////////// LETTER LOOP LOOP
if($_set->action == "batch.cancel" && $_set->type=="letter") {
	?>
	
	letter_amount = 0;
	xhttp.gfx("cancelled!", ref.trg+".response");
	$(ref.trg).value = "continue send loop";
	$(ref.trg).vars.action = "batch.loop";
	clearTimeout( $(ref.trg).tm );
		
	<?
exit(); }

////////////////// LETTER LOOP END
if($_set->action == "loop.end" && $_set->type=="letter") {

	?>
	xhttp.gfx("all done, go home.", ref.trg+".response");
	$(ref.trg).value = "send loop again";
	$(ref.trg).disabled = true;
	<?
exit(); }





*/


